/**
 * Created by Adam on 2017/5/18.
 */
import React from 'react'
import {connect} from 'react-redux'
import {browserHistory} from 'react-router'
import {Paper, Menu, MenuItem, MuiThemeProvider, Drawer, AppBar, FlatButton, IconButton} from 'material-ui'
import PersonAdd from 'material-ui/svg-icons/social/person-add';
import Person from 'material-ui/svg-icons/social/person'
import Group from 'material-ui/svg-icons/social/group'
import ExitButton from 'material-ui/svg-icons/action/power-settings-new'
import {toggleSideBar, logout} from '../actions'

const styles = {
    openContainer: {
        width: '70%', maxHeight: '600px', marginLeft: '30%'
    },
    closeContainer: {
        width: '100%', maxHeight: '600px', marginLeft: '0'
    }
};

class Logout extends React.Component {
    logoutHandler = () => {
        console.log('be going to logout')
        const { dispatch } = this.props
        dispatch(logout())
        browserHistory.push('/login')
    }

    render() {
        return (
            <FlatButton label="LOGOUT" icon={<ExitButton/>} onClick={this.logoutHandler}/>
        )
    }
}
Logout = connect()(Logout)

class Root extends React.Component {
    componentDidUpdate(prevProps) {
        const {redirectUrl} = this.props
        const isLoggingIn = !prevProps.isLoggedIn && this.props.isLoggedIn

        if (isLoggingIn) {
            browserHistory.push(redirectUrl)
        }
    }

    toggleSideBarFunc = () => {
        const {dispatch} = this.props
        dispatch(toggleSideBar())
    }

    menuClickHandler = (event, menuItem, index) => {
        console.log('click menuItem ' + index)
    }

    render() {
        const {dispatch, isSideBarOpen} = this.props
        return (
            <MuiThemeProvider>
                <div>
                    <Drawer open={isSideBarOpen}>
                        <Menu onItemTouchTap={this.menuClickHandler}>
                            <MenuItem primaryText="Users" leftIcon={<Person/>}/>
                            <MenuItem primaryText="Logout" leftIcon={<ExitButton/>}/>
                        </Menu>
                    </Drawer>
                    <div style={isSideBarOpen ? styles.openContainer : styles.closeContainer}>
                        <AppBar title="React Admin" onLeftIconButtonTouchTap={this.toggleSideBarFunc} iconElementRight={<Logout/>}/>
                        {this.props.children}
                    </div>
                </div>

            </MuiThemeProvider>
        )
    }
}

const mapStateToProps = (state) => {
    return {
        isLoggedIn: state.isLoggedIn,
        redirectUrl: state.redirectUrl,
        isSideBarOpen: state.isSideBarOpen
    }
}

export default connect(mapStateToProps)(Root)